import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    WebView,
    Dimensions,
    Image,
    Text,
    NativeModules,
    TouchableOpacity,
    DeviceEventEmitter,
    Platform,
    Clipboard, PermissionsAndroid
} from 'react-native';

import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import ToastUtils from '../Utils/ToastUtils'
import HttpUtils from '../Utils/HttpUtils'
import RouterUtils from "../Utils/RouterUtils";
import ShareUtil from "../Umeng/ShareUtil";
import StorageUtils from "../Utils/StorageUtils";
import Constant from "../Constant/Constant";

export default class WebPage extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: navigation.state.params.title,
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (
            <TouchableOpacity onPress={() =>
            {
                navigation.state.params.reloadPage();
            }}>
                <Image resizeMode={Image.resizeMode.stretch} style={{width: 40, height: 23, marginRight: 8}} source={require('../img/refresh.png')}/>
            </TouchableOpacity>
        ),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            textAlign: 'center'
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            url: this.props.navigation.state.params.url
        };
    }

    componentDidMount()
    {
        this.props.navigation.setParams({
            reloadPage: this.reloadPage
        });
        RouterUtils.pushRouter('WebPage', this.props.navigation.state.key);
        if (Platform.OS == 'android')
        {
            // this.getLocation();
            if (this.props.navigation.state.params.title == '当前位置')
            {
                this.requestLocationPermission();
            }
        }
    }

    componentWillUnmount()
    {
        RouterUtils.popRouter('WebPage', this.props.navigation.state.key);
    }

    async requestLocationPermission()
    {
        try
        {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '获取定位权限',
                    'message': '允许获取定位权限'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED)
            {
                // this.show("你已获取了地址查询权限")
            } else
            {
                this.show("获取地址查询失败")
                ToastUtils.toastShortBottom('获取定位权限失败，请重试')
            }
        }
        catch (err)
        {
            this.show(err.toString())
        }
    }

    handleMessage(e)
    {
        let data = JSON.parse(e.nativeEvent.data);
        console.log('WebPage handleMessage:' + JSON.stringify(data));
        if (data.type == '定位')
        {
            DeviceEventEmitter.emit('postLocation', JSON.stringify(
                {
                    'geolocation': data.geolocation, 'address': data.address, 'grid': data.grid,
                }));
            this.props.navigation.goBack();
        }
    }

    onBack()
    {
        this.refs["webView"].goBack();
    }

    onForward()
    {
        this.refs["webView"].goForward();
    }

    //自定义返回事件
    reloadPage = () =>
    {
        this.refs["webView"].reload();
    };

    render()
    {
        const patchPostMessageFunction = function ()
        {
            var originalPostMessage = window.postMessage;

            var patchedPostMessage = function (message, targetOrigin, transfer)
            {
                originalPostMessage(message, targetOrigin, transfer);
            };

            patchedPostMessage.toString = function ()
            {
                return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
            };

            window.postMessage = patchedPostMessage;
        };

        const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';

        return (
            <View style={styles.container}>
                <WebView
                    style={styles.web}
                    source={{uri: this.state.url, method: 'GET', headers: {'Cache-Control': 'no-cache'}}}
                    ref="webView"
                    startInLoadingState={true}
                    domStorageEnabled={true}
                    javaScriptEnabled={true}
                    onMessage={(e) =>
                    {
                        this.handleMessage(e)
                    }}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: ColorUtils.bgColor,
    },
    web: {
        flex: 1,
    },
});



